package main

import (
	"context"
	"encoding/base64"
	"fmt"
	"os"
	"strconv"
	"strings"
	"time"
	"wails/sudoku"
)

// App struct
type App struct {
	ctx context.Context
}

// NewApp creates a new App application struct
func NewApp() *App {
	return &App{}
}

// startup is called when the app starts. The context is saved,
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) {
	a.ctx = ctx
}

type Options struct {
	Difficulty int `json:"difficulty"`
}

type Board struct {
	Solution []int `json:"solution"`
	Subject  []int `json:"subject"`
}

// Generate 生成数独迷题
func (a *App) Generate(options Options) Board {

	if options.Difficulty >= 0 && options.Difficulty < 5 {
		solution, subject, length := sudoku.Generate(options.Difficulty)

		fmt.Println(`solution`, solution)
		fmt.Println(`subject`, subject)
		fmt.Println(`options`, options, length)

		return Board{solution, subject}
	} else {
		return Board{
			Solution: []int{
				6, 4, 9, 3, 2, 8, 5, 7, 1,
				3, 5, 1, 6, 9, 7, 8, 2, 4,
				7, 8, 2, 5, 1, 4, 6, 3, 9,
				4, 6, 5, 8, 7, 1, 2, 9, 3,
				2, 1, 7, 9, 6, 3, 4, 5, 8,
				9, 3, 8, 4, 5, 2, 7, 1, 6,
				8, 9, 3, 7, 4, 5, 1, 6, 2,
				1, 7, 4, 2, 3, 6, 9, 8, 5,
				5, 2, 6, 1, 8, 9, 3, 4, 7,
			},
			Subject: []int{
				0, 4, 9, 3, 2, 8, 5, 7, 1,
				3, 0, 1, 6, 9, 7, 8, 2, 4,
				7, 8, 0, 5, 1, 4, 6, 3, 9,
				4, 6, 5, 0, 7, 1, 2, 9, 3,
				2, 1, 7, 9, 0, 3, 4, 5, 8,
				9, 3, 8, 4, 5, 0, 7, 1, 6,
				8, 9, 3, 7, 4, 5, 0, 6, 2,
				1, 7, 4, 2, 3, 6, 9, 0, 5,
				5, 2, 6, 1, 8, 9, 3, 4, 0,
			},
		}
	}

}

// Levels 返回游戏难度级别选项
func (a *App) Levels() []sudoku.Level {
	return sudoku.Levels
}

// Screenshot 保存游戏截图
func (a *App) Screenshot(rawBase64 string) bool {
	dir, _ := os.Getwd()
	timeStr := strconv.FormatInt(time.Now().Unix(), 10)
	filename := dir + "/sudoku-game-screenshot-" + timeStr + ".png"

	str := strings.Replace(rawBase64, "data:image/png;base64,", "", 1)
	data, _ := base64.StdEncoding.DecodeString(str)

	err := os.WriteFile(filename, data, 0644)
	return err == nil
}
